﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using GCC.APIContainer.Utilities;
using GCC.Container.Abstracts;
using GCC.Container.Models;

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

using MySqlX.XDevAPI.Common;

using Newtonsoft.Json;

using tcm.entity;
using tcm.entity.Device;
using tcm.Filters;
using tcm.request;
using tcm.response;
using tcm.utils;

using Result = tcm.response.Result;

namespace tcm.Controller
{
    [ApiController]
    [Route("tcm/report")]
    public class ReportController : GCCAPIControllerBase
    {
        public ReportController(AbsGCCContext context) : base(context)
        {
        }

        [HttpGet("queryByOrderId")]
        [TCMAuth(permission: "facility")]
        public ReportRes queryByOrderId(long order_no)
        {
            ReportRes res = new ReportRes();

            List<UserReport> userReoprtList = GCCEntrance.DBManager.GlobalDB.Select<UserReport>()
                .Where(a => a.order_id == order_no)
                .Where(a => a.status == 1).ToList();
            if (userReoprtList != null && userReoprtList.Count > 0)
            {
                res.userReport = userReoprtList.First();
                List<User> userList = GCCEntrance.DBManager.GlobalDB.Select<User>()
                   .Where(a => a.status == 1)
                   .Where(a => a.id == userReoprtList.First().user_id).ToList();
                if (userList == null || userList.Count == 0)
                {
                    res.msg = "User信息为空！";
                    res.code = 1;
                    return res;
                }

                res.user = userList.First();

                List<SysUser> doctorList = GCCEntrance.DBManager.GlobalDB.Select<SysUser>()
                   .Where(a => a.status == 1)
                   .Where(a => a.id == userReoprtList.First().doctor_id).ToList();
                if (doctorList != null && doctorList.Count > 0)
                {
                    res.doctor = doctorList.First();
                }

                res.code = GlobalConstant.Success;
                res.msg = "成功";
            }
            else
            {
                res.msg = "Report信息为空！";
                res.code = 1;
                return res;
            }

            return res;

        }

        [HttpGet("queryHis")]
        public DataResponse<List<ReportHis>> queryReport([FromQuery] ReportHisReq req) {
            var userReoprtList = GCCEntrance.DBManager.GlobalDB.Select<User, UserReport, SysUser>()
                .InnerJoin((a, b, c) => a.id == b.user_id)
                .LeftJoin((a, b, c) => b.doctor_id == c.id && c.is_delete == 0)
                .Where((a, b, c) => a.status == 1)
                .WhereIf(!string.IsNullOrEmpty(req.wxId), (a, b, c) => a.wx_id == req.wxId)
                .WhereIf(req.userId != null, (a, b, c) => a.id == req.userId)
                .WhereIf(!string.IsNullOrEmpty(req.userName), (a, b, c) => a.uname.Contains(req.userName))
                .WhereIf(req.beginTime != null, (a, b, c) => b.create_date >= req.beginTime)
                .WhereIf(req.endTime != null, (a, b, c) => b.create_date <= req.endTime)
                .OrderByDescending((a, b, c) => b.create_date)
                .Count(out var count)
                .Page(req.PageIndex ?? 1, req.PageSize)
                .ToList((a, b, c) => new { a, b, c });
                //.ToList(a => new
                //    {
                //        userName = "a.uname",
                //        bid = "b.Id",
                //        userId = "b.user_id",
                //        orderId = "b.order_id",
                //        price = "b.price",
                //        remark = "b.price",
                //        doctorId = "b.doctor_id",
                //        status = "b.status",
                //        imgUrl = "b.img_url"
                //    });


            List<ReportHis> list = new List<ReportHis>();
            for (int i = 0; i < userReoprtList.Count; i++)
            { 
                var userReport = userReoprtList[i];
                ReportHis report = new ReportHis();
                //report.userName = userReport.a.uname;
                //report.userId = userReport.b.user_id;
                //report.orderId = userReport.b.order_id;
                //report.price = userReport.b.price;
                //report.remark = userReport.b.remark;
                //report.doctorId = userReport.b.doctor_id;
                //report.createTime = userReport.b.create_date;

                report.user = userReport.a;
                report.report = userReport.b;
                report.doctor = userReport.c;

                //密码设置成空
                if (report.doctor != null) {
                    report.doctor.password = "";
                }
                
                list.Add(report);
            }
            return HandleData(list, count);
        }


        [HttpGet("detail")]
        public ReportDetailRes querydetail(long reportId)
        {
            var userReoprtList = GCCEntrance.DBManager.GlobalDB.Select<User, UserReport, SysUser>()
                .InnerJoin((a, b, c) => a.id == b.user_id)
                .LeftJoin((a, b, c) => b.doctor_id == c.id && c.is_delete == 0)
                .Where((a, b, c) => a.status == 1)
                .Where((a, b, c) => b.id == reportId)
                .ToList((a, b, c) => new { a, b, c });

            ReportDetailRes reportDetailRes = new ReportDetailRes();
            if (userReoprtList != null && userReoprtList.Count > 0) 
            {
                reportDetailRes.user = userReoprtList[0].a;
                reportDetailRes.report = userReoprtList[0].b;
                reportDetailRes.doctor = userReoprtList[0].c;
            }

            // 获取药品信息
            var phmListQuery = GCCEntrance.DBManager.GlobalDB.Select<Pharmaceutical, UesrPhmList, UserReport>()
                .InnerJoin((a, b, c) => a.id == b.phm_id)
                .InnerJoin((a, b, c) => b.order_id == c.order_id)
                .Where((a, b, c) => c.id == reportId)
                .ToList((a, b, c) => new { a, b });

            if (phmListQuery != null)
            {
                List<UserPhm> phmList = new List<UserPhm>();
                for (int i = 0; i < phmListQuery.Count; i++)
                {
                    UserPhm userPhm = BeanUtils.copy<UserPhm, Pharmaceutical>(phmListQuery[i].a);
                    userPhm.num = phmListQuery[i].b.num;
                    phmList.Add(userPhm);
                }

                reportDetailRes.phmList = phmList;
            }
            return reportDetailRes;
        }


        [HttpGet("queryReportByWxId")]
        public ReportRes queryReportByWxId(string wxId)
        {
            ReportRes res = new ReportRes();
            List<User> userList = GCCEntrance.DBManager.GlobalDB.Select<User>()
                .Where(a => a.status == 1)
                .Where(a => a.wx_id == wxId).ToList();
            if (userList == null || userList.Count == 0)
            {
                res.msg = "User信息为空！";
                res.code = 1;
                return res;
            }

            res.user = userList.First();

            List<UserReport> userReoprtList = GCCEntrance.DBManager.GlobalDB.Select<UserReport>()
                .Where(a => a.user_id == userList.First().id)
                .Where(a => a.status == 1).ToList();
            if (userReoprtList != null && userReoprtList.Count > 0)
            {
                List<SysUser> sysUserList = GCCEntrance.DBManager.GlobalDB.Select<SysUser>()
                    .Where(a => a.id == userReoprtList.First().doctor_id)
                    .Where(a => a.is_delete == 0).ToList();
                if (sysUserList != null) 
                {
                    res.doctor = sysUserList.First();
                }
                res.userReport = userReoprtList.First();
                res.code = GlobalConstant.Success;
                res.msg = "成功";
            }
            else
            {
                res.msg = "Report信息为空！";
                res.code = 1;
                return res;
            }

            return res;
        }


        [HttpPost("uploadImg")]
        [TCMAuth(permission: "facility")]
        public Result uploadImg(ImgRequest requeset)
        {
            Result result = new Result();
            result.code = GlobalConstant.Success;
            try
            {
                List<Image> imageList = requeset.images;
                if (imageList == null || imageList.Count == 0)
                {
                    result.code = 1;
                    result.msg = "上传图片为空！";
                    return result;
                }

                long userId = requeset.user_id;
                List<User> list = GCCEntrance.DBManager.GlobalDB.Select<User>().Where(a => a.id == userId).ToList();
                if (list == null || list.Count == 0)
                {
                    result.code = 1;
                    result.msg = "用户数据中中没有userId:" + userId + "的数据！";
                    return result;
                }

                // 根据mac获取site_id
                List<Site> siteList = GCCEntrance.DBManager.GlobalDB.Select<Site>().Where(a => a.mac == requeset.mac).ToList();

                bool isNew = false;
                List<Order> orderLaterList = GCCEntrance.DBManager.GlobalDB.Select<Order>().Where(a => a.type == 0).Where(a => a.user_id == userId).Where(a => new[] {0, 1, 2, 3, 4, 5 }.Contains(a.status)).ToList();
                if (orderLaterList != null && orderLaterList.Count > 0)
                {
                    // 存在0未完成、1待发药 2待配送 3.配送中 4.配送完成 5.待客户取药的订单，判断订单是否大于7天
                    Order orderLater = orderLaterList.First();
                    DateTime day7 = DateTime.Now.AddDays(-7);
                    if (orderLater.create_date < day7)
                    {
                        _ = GCCEntrance.DBManager.GlobalDB.Update<Order>().Set(a => a.status == 7).Where(a => a.id == orderLater.id).ExecuteAffrows();
                        _ = GCCEntrance.DBManager.GlobalDB.Update<UserReport>().Set(a => a.status == 3).Where(a => a.order_id == orderLater.id).ExecuteAffrows();
                        isNew = true;
                    }
                    else 
                    {
                        isNew = false;
                    }
                }
                else
                {
                    //  6.完成 7.异常结束 或者没有订单
                    isNew = true;
                }

                UserReport userReport = null;
                long orderId = 0;
                if (isNew)
                {
                    // 生成order信息
                    orderId = setAddOrder(userId, siteList);
                    // 生成report信息，不入库
                    userReport = setReport(userId, orderId);
                }
                else
                {
                    result.msg = "该用户有未完成订单，请先完成该订单！";
                    result.code = GlobalConstant.Failure;
                    result.id = userId;
                    return result;
                }

                string uploadFilePath = Environment.GetEnvironmentVariable("uploadFilePath") ?? "";

                // 图片预览
                string showPic = Environment.GetEnvironmentVariable("showPic") ?? "";

                // 目录分割符
                string separator = getSeparator(uploadFilePath);

                StringBuilder stringBuffer = new StringBuilder();
                //上传文件
                for (int i = 0; i < imageList.Count; i++)
                {
                    Image image = imageList[i];
                    long id = IdUtils.getId(i);

                    // imgData为base64位码
                    String imgData = image.url;
                    byte[] data = Convert.FromBase64String(imgData);

                    // 保存到文件
                    FileUtils.createFilePath(uploadFilePath + separator + id);
                    String path = uploadFilePath + separator + id + separator +"image.png";
                    
                    FileStream fs = new FileStream(path, FileMode.Create);
                    fs.Write(data, 0, data.Length);
                    fs.Dispose();

                    // 根据path获取图片下载链接、
                    _=stringBuffer.Append(showPic + "/" + id + "/image.png").Append(",");
                }

                String img_url = stringBuffer.ToString();
                userReport.img_url = img_url.Substring(0, img_url.Length - 1);

                int reportInsert = GCCEntrance.DBManager.GlobalDB.Insert(userReport).ExecuteAffrows();

                if (reportInsert <= 0)
                {
                    result.code = GlobalConstant.Failure;
                    result.msg = "保存失败！";
                    //retrun result;
                }

                result.msg = "保存成功";
                result.id = userReport.order_id;

            }
            catch (Exception e)
            {
                result.code = 1;
                result.msg = e.Message;
            }

            return result;
        }

        private long setAddOrder(long userId, List<Site> siteList)
        {
            long orderId = IdUtils.getId();
            Order order = new Order();
            order.id = orderId;
            order.user_id = userId;
            order.status = 0;
            order.type = 0;
            order.create_date = DateTime.Now.ToLocalTime();
            order.update_date = DateTime.Now.ToLocalTime();

            if (siteList != null && siteList.Count > 0)
            {
                order.site_id = siteList.First().id;
            }

            int orderInsert = GCCEntrance.DBManager.GlobalDB.Insert(order).ExecuteAffrows();
            Console.WriteLine(orderInsert);
            return orderId;
        }

        private UserReport setReport(long userId, long orderId)
        {
            // 新增
            long reportId = IdUtils.getId();
            UserReport report = new UserReport();
            report.id = reportId;
            report.user_id = userId;
            report.order_id = orderId;
            report.status = 0;

            report.create_by = userId;
            report.create_date = DateTime.Now.ToLocalTime();
            report.update_by = userId;
            report.update_date = DateTime.Now.ToLocalTime();

            return report;

        }

        private string getSeparator(string uploadFilePath)
        {
            if (uploadFilePath.Contains("/"))
            {
                return "/";
            }
            else 
            {
                return "\\";
            }
        }

        //[HttpPost("uploadFile")]
        //public UploadFileResult uploadFile(IFormFile file)
        //{
        //    UploadFileResult result = new UploadFileResult();
        //    result.code = 200;
        //    try
        //    {
        //        string fileName = file.FileName;
        //        // 判断是否图片，不是图片，返回异常

        //        string uploadFilePath = Environment.GetEnvironmentVariable("uploadFilePath") ?? "";

        //        string tcmUrl = Environment.GetEnvironmentVariable("tcmUrl") ?? "";

        //        string filePath = IdUtils.getStringId();
        //        // 判断目录存在，不存在，创建
        //        FileUtils.createFilePath(uploadFilePath + "\\" + filePath);

        //        file.CopyTo(new FileStream(uploadFilePath + "\\" + filePath + "\\" + fileName, FileMode.Create));
        //        result.url = tcmUrl + "tcm/report/showImage/" + filePath + "\\" + fileName;
        //    }
        //    catch (Exception e)
        //    {
        //        result.code = 1;
        //        result.msg = e.Message;
        //    }

        //    return result;
        //}

        [HttpGet("query")]
        public DataResponse<List<UserReport>> query([FromQuery] QueryUserReportReq req)
        {
            return HandleData(GCCEntrance.DBManager.GlobalDB.Select<UserReport>()
                .WhereIf(req.id != null, a => a.id == req.id)
                .WhereIf(req.user_id != null, a => a.user_id == req.user_id)
                .WhereIf(req.order_id != null, a => a.order_id >= req.order_id)
                .WhereIf(req.doctor_id != null, a => a.doctor_id <= req.doctor_id)
                .WhereIf(req.status != null, a => a.status == req.status).OrderBy(a => a.update_date).ToList());
        }


        [HttpGet("manage/{doctorId}")]
        public ReportManageRes manage([FromRoute] long doctorId)
        {
            ReportManageRes res = new ReportManageRes();
            res.code = GlobalConstant.Success;
            res.msg = "成功！";

            List<UserReport> list = GCCEntrance.DBManager.GlobalDB.Select<UserReport>()
               .Where(a => a.status == 0).OrderBy(a => a.update_date).ToList();

            // 查询该医生下面待处理的数据
            List<UserReport> doctorList = GCCEntrance.DBManager.GlobalDB.Select<UserReport>()
               .Where(a => a.status == 2).Where(a => a.doctor_id == doctorId).ToList();
            if (doctorList == null || doctorList.Count == 0)
            {
                if (list == null || list.Count == 0)
                {
                    res.count = 0;
                    res.code = GlobalConstant.Failure;
                    res.msg = "没有待处理的检查报告！";
                    return res;
                }

                UserReport report = list[0];
                report.doctor_id = doctorId;
                report.status = 2;
                report.update_date = DateTime.Now;
                report.update_by = doctorId;

                int m = GCCEntrance.DBManager.GlobalDB.Update<UserReport>(report.id).SetSource(report).ExecuteAffrows();
                if (m <= 0)
                {
                    res.code = GlobalConstant.Failure;
                    res.msg = "更新订单占用状态失败！";
                }

                res.report = report;
            }
            else 
            {
                res.report = doctorList[0];
            }

            // 查询病人user信息
            List<User> userList = GCCEntrance.DBManager.GlobalDB.Select<User>()
              .Where(a => a.id == res.report.user_id).ToList();
            if (userList != null && userList.Count > 0)
            {
                res.user = userList[0];
            }

            res.count = list.Count;
            return res;
        }

        [HttpPost("manage")]
        public Result manage(ReportManageReq req)
        {
            Result res = new Result();
            res.code = GlobalConstant.Success;
            res.msg = "成功！";

            List<UserReport> list = GCCEntrance.DBManager.GlobalDB.Select<UserReport>()
                .Where(a => a.status == 2).Where(a => a.id == req.reportId).ToList();
            if (list == null || list.Count == 0)
            {
                res.code = GlobalConstant.Failure;
                res.msg = "没有待处理的检查报告！";
                return res;
            }

           
            UserReport report = list[0];
            report.status = 1;
            report.update_date = DateTime.Now;
            report.remark = req.reportResult;

            List<Order> orderList = GCCEntrance.DBManager.GlobalDB.Select<Order>().Where(a => a.id == report.order_id).ToList();
            if (orderList == null || orderList.Count == 0)
            {
                res.code = GlobalConstant.Failure;
                res.msg = "检查报告无法关联订单信息！";
                return res;
            }

            var phmList = GCCEntrance.DBManager.GlobalDB.Select<Pharmaceutical, PhmListRelation>()
                .InnerJoin((a, b) => a.id == b.phm_id).Where((a, b) => b.phm_list_id == req.phmListId).ToList((a, b) => new { a, b});
            if (phmList == null || phmList.Count == 0) 
            {
                res.code = GlobalConstant.Failure;
                res.msg = "根据药方id无法查询药品信息！";
                return res;
            }

            // 药品总价
            Decimal price = 0;
            
            // 关联药方和订单信息
            List<UesrPhmList> uesrPhmLists = new List<UesrPhmList>();
            for (int i = 0; i < phmList.Count; i++) 
            {
                UesrPhmList userPhmList = new UesrPhmList();
                userPhmList.id = IdUtils.getId(i);
                userPhmList.phm_id = phmList[i].a.id;
                userPhmList.phm_list_id = req.phmListId;
                userPhmList.num = phmList[i].b.phm_num;
                userPhmList.order_id = report.order_id;
                userPhmList.create_date = DateTime.Now;
                userPhmList.create_by = report.doctor_id;
                userPhmList.update_date = DateTime.Now;
                userPhmList.update_by = report.doctor_id;
                uesrPhmLists.Add(userPhmList);

                Decimal phmPrice = Convert.ToDecimal(phmList[i].a.price);
                price = Decimal.Add(price, Decimal.Multiply(phmList[i].b.phm_num, phmPrice));
            }
            _=GCCEntrance.DBManager.GlobalDB.Insert<UesrPhmList>(uesrPhmLists).ExecuteAffrows();

            Order order = orderList[0];
            order.price = Decimal.ToDouble(price);

            // 查询site_id下面的药斗存在处方和phmListId相同的药斗
            //var phmCabinetList = GCCEntrance.DBManager.GlobalDB.Select<Site, Device, Cabinet>()
            //    .InnerJoin((b, c, d) => b.id == c.site_id && c.type == 2)
            //    .InnerJoin((b, c, d) => c.id == d.device_id)
            //    .Where((b, c, d) => b.id == order.site_id)
            //    .Where((b, c, d) => d.phm_list_id == req.phmListId).ToList();
            //if (phmCabinetList != null && phmCabinetList.Count > 0)
            //{
            //    // 存在，则订单状态修改为取药，是否预约状态更新为 “否”
            //    order.status = 5;
            //    order.is_apply = 0;
            //}
            //else
            //{
            //    // 与药斗处方不同，与药斗不同，则说明是药柜，所有药柜都是需要预约的（直接让预约），订单状态是待发药、是否预约是
            //    order.status = 1;
            //    order.is_apply = 1;
            //}

            order.status = 5;
            order.is_apply = 0;
            _ = GCCEntrance.DBManager.GlobalDB.Update<Order>(order.id).SetSource(order).ExecuteAffrows();

            int m = GCCEntrance.DBManager.GlobalDB.Update<UserReport>(report.id).SetSource(report).ExecuteAffrows();
            if (m <= 0)
            {
                res.code = GlobalConstant.Failure;
                res.msg = "更新报告状态失败！";
            }
            res.msg = "成功, price:" + Decimal.ToDouble(price).ToString();
            return res;
        }

        [HttpGet("close/{reportId}")]
        public Result close([FromRoute] long reportId)
        {
            Result res = new Result();
            res.code = GlobalConstant.Success;
            res.msg = "关闭成功！";

            List<UserReport> list = GCCEntrance.DBManager.GlobalDB.Select<UserReport>()
                .Where(a => a.id == reportId).Where(a => a.status == 2).ToList();
            if (list == null || list.Count == 0)
            {
                res.code = GlobalConstant.Failure;
                res.msg = "检查报告不是占用状态，无法关闭！";
                return res;
            }

            UserReport report = list[0];
            report.status = 3;
            report.update_date = DateTime.Now;

            int m = GCCEntrance.DBManager.GlobalDB.Update<UserReport>(report.id).SetSource(report).ExecuteAffrows();
            if (m <= 0)
            {
                res.code = GlobalConstant.Failure;
                res.msg = "更新订单关闭状态失败！";
            }
            var saveRes = GCCEntrance.DBManager.GlobalDB.Update<Order>(report.order_id)
               .Set(item => item.status,7)
               .ExecuteAffrows()==1;

            return res;
        }


        [HttpPost("add")]
        public Result addUserReport(UserReportRequest reportRequest)
        {
            Result result = new Result();
            result.code = GlobalConstant.Success;

            UserReport report = BeanUtils.copy<UserReport, UserReportRequest>(reportRequest);
            long reportId = IdUtils.getId();
            report.id = reportId;
            report.create_date = DateTime.Now.ToLocalTime();
            report.update_date = DateTime.Now.ToLocalTime();

            // 设置有效
            report.status = 0;

            int m = GCCEntrance.DBManager.GlobalDB.Insert<UserReport>(report).ExecuteAffrows();
            if (m <= 0)
            {
                result.code = 1;
                result.msg = "入库失败！";
            }

            result.msg = report.ToString();
            result.id = reportId;
            return result;
        }

        [HttpPut("update")]
        public Result updateUserReport(UserReportRequest reportRequest)
        {
            Result result = new Result();
            result.code = GlobalConstant.Success;
            updateReport(reportRequest, result);

            return result;
        }

        private void updateReport(UserReportRequest reportRequest, Result result)
        {
            long reportId = reportRequest.id;
            result.id = reportId;
            if (reportId == null)
            {
                result.code = 1;
                result.msg = "id为空!";
            }

            try
            {
                List<UserReport> list = GCCEntrance.DBManager.GlobalDB.Select<UserReport>().Where(a => a.id == reportId).ToList();
                if (list == null || list.Count == 0)
                {
                    result.code = 1;
                    result.msg = "数据库中没有id:" + reportId + "的数据！";
                    return;
                }

                UserReport userReport = list.First();
                BeanUtils.copy<UserReport, UserReportRequest>(reportRequest, ref userReport);
                result.msg = userReport.ToString();

                userReport.update_date = DateTime.Now.ToLocalTime();

                result.id = reportId;

                int m = GCCEntrance.DBManager.GlobalDB.Update<UserReport>(reportId).SetSource(userReport).ExecuteAffrows();
                if (m <= 0)
                {
                    result.code = 1;
                    result.msg = "更新失败！";
                }
            }
            catch (Exception e)
            {
                result.code = 1;
                result.msg = e.Message;
            }
        }
    }
}
